package com.fzshang.commen.util.zhifubao;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * Created by 张子艺 on 2018/9/14.
 *
 */
public class SysSetUtil {


    // 商户appid     // TODO: 2018/9/14  这里需要替换
    public static String APPID = "2016092300577552";
    // 私钥 pkcs8格式的
    //public static String RSA_PRIVATE_KEY = "此处省略若干字";
    // 服务器异步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //  public static String notify_url = "此处省略若干字";
    // 页面跳转同步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 商户可以自定义同步跳转地址
    public static String return_url = "http://cmsrlpwehz.51http.tech/payment/aliPaySuccess";      // TODO: 2018/9/14  这里需要替换
    // 请求网关地址             // TODO: 2018/9/14  这里需要替换
    public static String ALIURL = "https://openapi.alipaydev.com/gateway.do";
    // 编码
    public static String CHARSET = "UTF-8";
    // 返回格式
    public static String FORMAT = "json";
    // 商户私钥  对 公钥   和 阿里公钥      // TODO: 2018/9/14  这里需要替换
    public static String RSA2_Private_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCQ7y/9rwFQvAv3YTkcIn+FXsf0HEMhFaWcfDUlsh0htL+YbLXr6LMZMc4UGJj/mwwkU44OfZLRqfMMJRkRvNZ8IhdPEDDOSAPTcnZUK/kSEyiyIiwyBFRMO43CKab7CGO7ip2ESsbp5rlGwiipIB3Lgm64TS2XwebJZKf5P6HMgVXtVd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KBfo3HrS+pO2/2Ik52muOMtViNmnKq8eQOSSC9l/9OzfYs6qfSg3wVNaZXgplgmAruZBBY4puP+0JfpHV/dqaQIDAQAB";
    // 日志记录目录
    public static String log_path = "/log";
    // RSA2
    public static String SIGNTYPE = "RSA2";

    /**
     *
     * @param moeny 商品价格
     * @param subject 商品名字
     * @param body body体中商品名字
     * @return 返回支付宝收银台页面
     */

    public static String Pay(String moeny,String subject,String body,String OrderNo){
        AlipayClient alipayClient = new DefaultAlipayClient(ALIURL, APPID, RSA2_Private_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY,SIGNTYPE); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
       //回调地址
        //alipayRequest.setReturnUrl(return_url);
        System.out.println("开始");
        alipayRequest.setNotifyUrl(return_url);//在公共参数中设置回跳和通知地址
        System.out.println("结束");
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+OrderNo+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+moeny+"," +
                "    \"subject\":\""+subject+"\"," +
                "    \"body\":\""+body+"\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return form;
    }

    /**
     * H5支付
     * @param OrderNo
     * @param moeny
     * @param subject
     * @return
     * @throws AlipayApiException
     */
    public static String h5Pay( String OrderNo,String moeny,String subject,String returnUrl,String NotifyUrl) throws    AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(ALIURL, APPID, RSA2_Private_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY,SIGNTYPE); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request

        // TODO: 2019/1/2 支付成功回调
       alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(NotifyUrl);//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "\"out_trade_no\":\""+OrderNo+"\"," +
                "\"total_amount\":"+moeny+"," +
                "\"subject\":\""+subject+"\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";

        form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单

        return  form;

    }
public  static  void main(String args[]){
    zhuanzhang("6000");
}



    /**
     * @param rechargeAmount
     * @return 转账
     */
    public static String zhuanzhang(String rechargeAmount){
        AlipayClient alipayClient = new DefaultAlipayClient(ALIURL, APPID, RSA2_Private_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY,SIGNTYPE); //获得初始化的AlipayClient
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();

        String outBizNo = OrderIdUtil.gen("AA",1L);

        //收款方
        String payeeAccount = "dbbits1353@sandbox.com";
        request.setBizContent("{" +
                "    \"out_biz_no\":\""+outBizNo+"\"," +
                "    \"payee_type\":\"ALIPAY_LOGONID\"," +
                "    \"payee_account\":\""+payeeAccount+"\"," +
                "    \"amount\":\""+rechargeAmount+"\"," +
                "    \"payer_show_name\":\"上海交通卡退款\"," +
                "    \"payee_real_name\":\"沙箱环境\"," +
                "    \"remark\":\"转账备注\"," +
                "  }");


        try {
            AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                return "调用成功";

            } else {
                System.out.println("调用失败");
                return "调用失败";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "123";
    }











    /**
     *
     * @param refoundBean 封装退款属性类
     * @return 退款状态
     * @throws AlipayApiException
     */
//    public static String Refound(RefoundBean refoundBean) throws AlipayApiException {
//        AlipayClient alipayClient = new DefaultAlipayClient(ALIURL, APPID, RSA2_Private_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY,SIGNTYPE);
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//      //把封装类转成JSON
//       String refoundJson= JSONObject.toJSONString(refoundBean);
//
//        request.setBizContent(refoundJson);
//        //退款
//        AlipayTradeRefundResponse response = alipayClient.execute(request);
//        //trade_no
//        System.out.println("response:"+response.getTradeNo());
//        if(response.isSuccess()){
//           return "success";
//        } else {
//            System.err.println(response.getMsg());
//            return "fail";
//        }
//    }

    /**
     * 下载对账单
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    public static String findOrder(String date) throws AlipayApiException, IOException {
      try {
          AlipayClient alipayClient = new DefaultAlipayClient(ALIURL, APPID, RSA2_Private_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGNTYPE); //获得初始化的AlipayClient
          AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();//创建API对应的request类
          request.setBizContent("{" +
                  "    \"bill_type\":\"trade\"," +
                  "    \"bill_date\":\""+date+"\"}"); //设置业务参数
          AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
          String billDownloadUrl=  response.getBillDownloadUrl();
          downBill(billDownloadUrl); //调用下载文件方法
          return "查询成功";
      }catch (Exception e){
          e.printStackTrace();
          return "查询失败，后台异常";
      }


    }


    /**
     * 下载账单文件：
     * @return response
     */
    // TODO: 2018/9/14 需要修改下载文件到哪里的路径
    public static  String downBill(String billDownloadUrl){
        long filename=new Date().getTime();
        //指定希望保存的文件路径
        String filePath = "F:/alipay/billfile/fund_bill_"+filename+".zip";
        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            url = new URL(billDownloadUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setConnectTimeout(5 * 1000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
            httpUrlConnection.connect();
            fis = httpUrlConnection.getInputStream();
            byte[] temp = new byte[1024];
            int b;
            fos = new FileOutputStream(new File(filePath));
            while ((b = fis.read(temp)) != -1) {
                fos.write(temp, 0, b);
                fos.flush();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fis!=null) fis.close();
                if(fos!=null) fos.close();
                if(httpUrlConnection!=null) httpUrlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }




}
